Namespace("sketch.ui.common");

(function(fwk, ui) {
    ui.common.Grid = klass(fwk.Container, {
        __type__: "ui.common.Grid",

        _constructor: function() {
            this.properties.createProperty("background", "Background color", null);
        },

        background: function(value){
            return this.properties.background(value);
        },

        canAccept: function(element){
            return true;
        },

        drawSelf : function($super, context) {
            var background = this.background();
            if (background) {
                context.save();
                context.fillStyle = background;
                context.fillRect(this.left(), this.top(), this.width(), this.height());
                context.restore();
            }

            $super(context);
        },

        arrange: function(){
            var l = this.left(),
                t = this.top(),
                w = this.width(),
                h = this.height();
            var that = this;
            var padding = this.padding();

            this.children.each(function(i, child){
                var left, top, width, height;
                var leftSpace = padding.left() + child.margin().left();
                var topSpace = padding.top() + child.margin().top();
                var rightSpace = padding.right() + child.margin().right();
                var bottomSpace = padding.bottom() + child.margin().bottom();

                switch (child.horizontalAlignment()){
                    case "left":
                        left = leftSpace;
                        break;
                    case "center":
                        left = w/2 - child.width()/2;
                        break;
                    case "right":
                        left = w - child.width() - rightSpace;
                        break;
                    case "stretch":
                        left = leftSpace;
                        width = w - leftSpace - rightSpace;
                        break;
                }

                switch (child.verticalAlignment()){
                    case "top":
                        top = topSpace;
                        break;
                    case "center":
                        top = h/2 - child.height()/2;
                        break;
                    case "bottom":
                        top = h - child.height() - bottomSpace;
                        break;
                    case "stretch":
                        top = topSpace;
                        height = h - topSpace - bottomSpace;
                        break;
                }

                child.left(left);
                child.top(top);
                child.width(width);
                child.height(height);
            });
        }
    });
})(sketch.framework, sketch.ui);